"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var BaseController_1 = require('./BaseController');
var UserRegisterDto_1 = require('../dtos/users/UserRegisterDto');
var UserLoginedDto_1 = require('../dtos/users/return/UserLoginedDto');
var UserUpdateDto_1 = require('../dtos/users/UserUpdateDto');
var UsersService_1 = require('../services/UsersService');
var UserController = (function (_super) {
    __extends(UserController, _super);
    function UserController(app) {
        _super.call(this, app);
        var $this = this;
        app.get(this.domain + "/users/login", function (req, res) {
            $this.handerErr(req, res, function () {
                $this.login(req, res);
            });
        });
        app.post(this.domain + "/users/register", function (req, res) {
            $this.handerErr(req, res, function () {
                $this.register(req, res);
            });
        });
        app.put(this.domain + "/users", function (req, res) {
            $this.handerErr(req, res, function (user) {
                $this.updateUserInfo(req, res, user);
            }, true);
        });
        this.usersService = new UsersService_1.UsersService();
    }
    UserController.prototype.login = function (req, res) {
        _super.prototype.initResponse.call(this, res);
        var username = req.header("x-username");
        var password = req.header("x-password");
        this.usersService.login(username, password, function (err, authUser) {
            if (!err && authUser) {
                var userLoginedDto = new UserLoginedDto_1.UserLoginedDto(authUser);
                res.send(JSON.stringify(userLoginedDto));
            }
            else {
                res.status(404);
                res.send({ msg: "error!" });
            }
        });
    };
    UserController.prototype.register = function (req, res) {
        _super.prototype.initResponse.call(this, res);
        this.usersService.register(UserRegisterDto_1.UserRegisterDto.toUser(req.body), function (err, user) {
            user.password = undefined;
            res.send(JSON.stringify(user));
        });
    };
    UserController.prototype.updateUserInfo = function (req, res, user) {
        var userId = user._id;
        var user = UserUpdateDto_1.UserUpdateDto.toUser(userId, req.body);
        this.usersService.update(user, function (err, user) {
            res.send(JSON.stringify(user));
        });
    };
    return UserController;
}(BaseController_1.BaseController));
exports.UserController = UserController;
